package cn.crex1.xiaomi.controller;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.crex1.xiaomi.common.UserStatusEnum;
import cn.crex1.xiaomi.service.UserService;
import cn.crex1.xiaomi.service.impl.UserServiceImpl;
import cn.crex1.xiaomi.util.CookieUtil;
import cn.crex1.xiaomi.util.DateUtil;
import cn.crex1.xiaomi.util.JsonUtils;
import cn.crex1.xiaomi.util.MD5Util;
import cn.crex1.xiaomi.util.RandomCodeUtil;
import cn.crex1.xiaomi.util.RedisUtil;
import cn.crex1.xiaomi.util.StringUtil;
import cn.crex1.xiaomi.vo.UserVO;

/**
 * 用户Controller
 * 
 * @author zzh
 *
 */
@WebServlet("/user/*")
public class UserController extends HttpServlet {

	private static final String _1 = "1";
	private static final String _0 = "0";
	private static final String STATE = "state";
	private static final String MSG = "msg";
	private static final String USERTOKENKEY = "utoken";

	private static final String EQUALSRANDOM_CODE = "equalsrandomCode";
	private static final String RANDOM_CODE = "randomCode";
	private static final String ISTELEPHONE = "istelephone";
	private static final String ISUSERNAME = "isusername";
	private static final String REGISTER = "register";
	private static final String LOGIN = "login";
	private static final String VALILOGIN = "valilogin";
	private static final String LOGINOUT = "loginout";

	private UserService userService = new UserServiceImpl();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String q[] = req.getRequestURI().split("/");
		if (q[3].equals(LOGIN)) {
			login(req, resp);
		} else if (q[3].equals(REGISTER)) {
			register(req, resp);
		} else if (q[3].equals(ISUSERNAME)) {
			selectUsername(req, resp);
		} else if (q[3].equals(ISTELEPHONE)) {
			selectTelephone(req, resp);
		} else if (q[3].equals(RANDOM_CODE)) {
			randomCode(req, resp);
		} else if (q[3].equals(EQUALSRANDOM_CODE)) {
			equqlsrandomCode(req, resp);
		} else if (q[3].equals(VALILOGIN)) {
			valilogin(req, resp);
		} else if (q[3].equals(LOGINOUT)) {
			loginout(req, resp);
		}
	}

	// 登录
	private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String telephone = req.getParameter("telephone");
		String password = req.getParameter("password");

		UserVO userVO = new UserVO();

		userVO.setTelephone(telephone);
		userVO.setPassword(MD5Util.MD5EncodeUtf8(password));

		String result = userService.selectUserByTelephoneAndPassword(userVO);
		Map<String, Object> map = new HashMap<>();
		if (StringUtil.isExists(result)) {
			if (result == UserStatusEnum.ALREADYLOGIN.getDesc()) {
				// 用户早已登录
				map.put(MSG, result);
				JsonUtils.writeJsonStringByResponse(resp, JsonUtils.writeJsonStringByMap(map));
				return;
			}
			if (result == UserStatusEnum.ACCOUNTERROR.getDesc()) {
				// 账号密码错误
				map.put(MSG, result);
				JsonUtils.writeJsonStringByResponse(resp, JsonUtils.writeJsonStringByMap(map));
				return;
			} else {
				// token值
				String cookieValue = CookieUtil.getCookieValue(req, USERTOKENKEY);
				if (StringUtil.isExists(cookieValue)) {
					if (!cookieValue.equals(result)) {
						map.put(MSG, UserStatusEnum.EERORLOGIN.getDesc());
						JsonUtils.writeJsonStringByResponse(resp, JsonUtils.writeJsonStringByMap(map));
						return;
					}
				} else {
					// 存入浏览器cookie
					CookieUtil.addCookie(resp, USERTOKENKEY, result, 86400);
					// session保存redis key
					HttpSession session = req.getSession();
					session.setAttribute(USERTOKENKEY, result);
					map.put(MSG, UserStatusEnum.LOGINSUCCESS.getDesc());
					JsonUtils.writeJsonStringByResponse(resp, JsonUtils.writeJsonStringByMap(map));
				}
			}
		} else {
			map.put(MSG,  result);
			JsonUtils.writeJsonStringByResponse(resp, JsonUtils.writeJsonStringByMap(map));
		}
	}

	// 注册
	private void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		String telephone = req.getParameter("telephone");
		String password = req.getParameter("password");
		String username = req.getParameter("username");

		// 获取时间，并转换为date格式
		Date date = DateUtil.converDateByDateTime(LocalDateTime.now());
		UserVO userVO = new UserVO();
		// long telephone=Long.parseLong(telephone);
		userVO.setTelephone(telephone);
		userVO.setPassword(MD5Util.MD5EncodeUtf8(password));
		userVO.setUpDate(date);
		userVO.setUsername(username);
		String result = userService.updateUserByUserNameAndPasswordAndTelephone(userVO);
		if (result.equals("成功")) {
			resp.sendRedirect(req.getContextPath() + "/pages/login.jsp");
		} else {
			resp.sendRedirect(req.getContextPath() + "register.jsp");
		}
	}

	// 查询是账户是否存在
	private void selectUsername(HttpServletRequest req, HttpServletResponse resp) throws JsonGenerationException, JsonMappingException, IOException {
		String username = req.getParameter("username");
		UserVO userVO = new UserVO();
		userVO.setUsername(username);
		String result = userService.selectUserByUserName(userVO);
		Map<String, String> map = new HashMap<String, String>();
		if (result.equals("未注册")) {
			map.put(STATE, _0);
		} else {
			map.put(STATE, _1);
		}
		JsonUtils.writeJsonStringByResponse(resp, JsonUtils.writeStringByObject(map));
	}

	// 查询是账户是否存在
	private void selectTelephone(HttpServletRequest req, HttpServletResponse resp) throws JsonGenerationException, JsonMappingException, IOException {
		String telephone = req.getParameter("telephone");
		UserVO userVO = new UserVO();
		userVO.setTelephone(telephone);
		String result = userService.selectUserByTelephone(userVO);
		Map<String, String> map = new HashMap<String, String>();
		if (result.equals("未使用")) {
			map.put(STATE, _0);
		} else {
			map.put(STATE, _1);
		}
		JsonUtils.writeJsonStringByResponse(resp, JsonUtils.writeStringByObject(map));
	}

	// 获取验证码
	protected void randomCode(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
		// 调用验证码工具类
		RandomCodeUtil.createRandomCode(req, resp);

	}

	// 对验证码进行比较
	protected void equqlsrandomCode(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
		// 调用验证码工具类
		Map<String, String> map = new HashMap<String, String>();
		if (RandomCodeUtil.equalsRandomCode(req)) {
			map.put(STATE, _0);
			JsonUtils.writeJsonStringByResponse(resp, JsonUtils.writeStringByObject(map));
		} else {
			map.put(STATE, _1);
			JsonUtils.writeJsonStringByResponse(resp, JsonUtils.writeStringByObject(map));
		}
	}

	private void valilogin(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
		String cookieValue = CookieUtil.getCookieValue(req, USERTOKENKEY);
		Map<String, Object> map=new HashMap<>();
		if (StringUtil.isExists(cookieValue) && RedisUtil.Keys.exists(cookieValue)) {
			// 获取用户手机号码
			// String telephone = RedisUtil.Strings.get(cookieValue).split("+")[1];
			// 获取用户id
			String userid = RedisUtil.Strings.get(cookieValue).split("\\+")[0];
			// 查询用户名
			String username = userService.selectUsernameByUserId(Integer.parseInt(userid));
			if (StringUtil.isExists(username)) {
				// 返回json数据
				map.put("userid", userid);
				map.put("username", username);
				map.put(STATE, _0);
				JsonUtils.writeJsonStringByResponse(resp, JsonUtils.writeJsonStringByMap(map));
			}
		} else {
			map.put(STATE, _1);
			JsonUtils.writeJsonStringByResponse(resp,JsonUtils.writeJsonStringByMap(map));
		}
	}

	private void loginout(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
		String id = req.getParameter("id");
		Map<String, Object> map=new HashMap<>();
		if (StringUtil.isExists(id)) {
			// 判断缓存中是否有对应的值 有则删除
			// 判断cookie中是否有对应的值 有则删除
			String cookieValue = CookieUtil.getCookieValue(req, USERTOKENKEY);
			if (StringUtil.isExists(cookieValue)) {
				// 获取用户手机号码
				String telephone = RedisUtil.Strings.get(cookieValue).split("\\+")[1];
				// 获取用户id
				String userid = RedisUtil.Strings.get(cookieValue).split("\\+")[0];
				if (id.equalsIgnoreCase(userid)) {
					RedisUtil.Keys.del(cookieValue);
					RedisUtil.Keys.del(USERTOKENKEY+telephone);
					CookieUtil.removeCookie(resp, USERTOKENKEY);
					map.put(MSG, "退出成功");
					JsonUtils.writeJsonStringByResponse(resp, JsonUtils.writeJsonStringByMap(map));					
				}else {
					map.put(MSG, "登录有误");
				}
			}
		}
	}
}
